package com.usian.common.mongo.service.impl;

import com.usian.common.exception.CatchConsumerException;
import com.usian.common.mongo.feign.UserFeign;
import com.usian.common.mongo.service.CommentService;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CommentServiceImpl  implements CommentService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        // 检查参数
        if(dto == null){
            CatchConsumerException.catchException(20003,"参数有误");
        }
        if(dto.getArticleId() == null){
            CatchConsumerException.catchException(20003,"参数有误");
        }
        if(dto.getContent() == null){
            CatchConsumerException.catchException(20003,"参数有误");
        }
        // 判断登录
        ApUser apUser =  AppThreadLocalUtils.getUser();
        if(apUser == null){
            CatchConsumerException.catchException(20003,"未登录不能评论");
        }
        apUser = userFeign.findUserById(apUser.getId());
        if(apUser == null){
            CatchConsumerException.catchException(20003,"未登录不能评论");
        }
        // 保存评论
        ApComment apComment = new ApComment();
        apComment.setImage(apUser.getImage());
        apComment.setCreatedTime(new Date());
        apComment.setAuthorName(apUser.getName());
        apComment.setAuthorId(apUser.getId());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setType(dto.getType());
        apComment.setUpdatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        mongoTemplate.insert(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
